package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.CheckgroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckgroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = CheckgroupService.class)
@Transactional
public class CheckgroupServiceImpl implements CheckgroupService {
    @Autowired
    private CheckgroupDao checkgroupDao;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup>page=checkgroupDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkgroupDao.add(checkGroup);
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);

    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkgroupDao.edit(checkGroup);
        checkgroupDao.deleteAssociation(checkGroup.getId());
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkgroupDao.findById(id);
    }

    @Override
    public void delete(Integer id) {
        long conut1=checkgroupDao.selectCountBycheckitemcheckgroupId(id);
        long conut2=checkgroupDao.selectCountBysetmealcheckgroupId(id);
        if (conut1>0 || conut2>0){
            throw new RuntimeException(MessageConstant.DELETE_CHECKGROUP_FAIL);
        }else {
            checkgroupDao.deleteById(id);
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkgroupDao.findAll();
    }

    @Override
    public List<Integer> selectCheckGroupsBySetmealId(Integer setmealId) {
        return checkgroupDao.selectCheckGroupsBySetmealId(setmealId);
    }


    public void setCheckGroupAndCheckItem(Integer checkGroupId, Integer[] checkitemIds){
        if (checkitemIds !=null && checkitemIds.length >0){
            for (Integer checkitemId : checkitemIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("checkgroup_id",checkGroupId);
                map.put("checkitem_id",checkitemId);
                checkgroupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }
}
